import type { ToolItem } from "~/types/tools";

/**
 * 查询API
 */
export default defineEventHandler(async (event) => {
  try {
        // 获取请求参数
        const query = getQuery(event);
        
        // 提取微信应用ID和密钥
        const q = query.q as string;    // 查询字符串
        
        // 构建微信API请求URL
        const url = `http://api.itoolsu.cn/api/search?q=${q}`;

        type ResData = ToolItem & {
            title: string;
            id: number;
        }
        
        // 调用微信接口获取AccessToken
        const res: { data: ResData[], success: boolean } = await $fetch(url);

        if (!res.success) {
            return {
                success: false,
                data: null,
            }
        }
        const tools = res.data.map(tool => ({
            ...tool,
            toolName: tool.title,
            toolId: tool.id,
        }))
        // 返回成功响应
        return {
            success: true,
            data: tools,
        }
    }
    catch (error) {
        // 错误处理：记录错误日志并返回500错误
        console.error('Database query error:', error)
        throw createError({
        statusCode: 500,
        statusMessage: '数据库查询失败'
        })
    }
});
